package com.yjc.hire.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.yjc.bo.CreateCompanyBO;
import com.yjc.bo.ModifyCompanyInfoBO;
import com.yjc.bo.QueryCompanyBO;
import com.yjc.bo.ReviewCompanyBO;
import com.yjc.hire.VO.CompanyInfoVO;
import com.yjc.hire.base.BaseInfoProperties;
import com.yjc.hire.enums.CompanyReviewStatus;
import com.yjc.hire.enums.YesOrNo;
import com.yjc.hire.exceptions.GraceException;
import com.yjc.hire.grace.result.PageGridResult;
import com.yjc.hire.grace.result.ResponseStatusEnum;
import com.yjc.hire.mapper.CompanyCustomMapper;
import com.yjc.hire.mapper.CompanyMapper;
import com.yjc.hire.mapper.CompanyPhotoMapper;
import com.yjc.hire.service.CompanyService;
import com.yjc.pojo.Company;
import com.yjc.pojo.CompanyPhoto;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * </p>
 *
 * @author jcyin
 * @since 2025/7/23
 * </p>
 */

@Service
public class CompanyServiceImpl extends BaseInfoProperties implements CompanyService {
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private CompanyCustomMapper companyCustomMapper;

    @Autowired
    private CompanyPhotoMapper companyPhotoMapper;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Company findCompanyByFullName(String fullName) {
        Company company = companyMapper.selectByFullName(fullName);
        return company;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createNewCompany(CreateCompanyBO companyBO) {
        Company company = new Company();
        BeanUtils.copyProperties(companyBO,company);
        company.setIsVip(YesOrNo.NO.type);
        company.setReviewStatus(CompanyReviewStatus.NOTHING.type);
        company.setCreatedTime(LocalDateTime.now());
        company.setUpdatedTime(LocalDateTime.now());
        companyMapper.insert(company);
        return company.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String resetCompany(CreateCompanyBO companyBO) {
        Company company = new Company();
        BeanUtils.copyProperties(companyBO,company);
        company.setId(companyBO.getCompanyId());
        company.setReviewStatus(CompanyReviewStatus.FAILED.type);
        company.setUpdatedTime(LocalDateTime.now());
        companyMapper.updateById(company);
        return company.getId();
    }

    @Override
    public Company getCompanyById(String companyId) {
        return companyMapper.getComById(companyId);
    }

    /*8
    审核提交信息的公司
     */
    @Transactional
    @Override
    public void commitReviewCompanyInfo(ReviewCompanyBO reviewCompanyBO) {
        Company pendingCompany = new Company();
        pendingCompany.setId(reviewCompanyBO.getCompanyId());
        pendingCompany.setReviewStatus(CompanyReviewStatus.REVIEW_ING.type);
        pendingCompany.setReviewReplay("");//审核意见
        pendingCompany.setAuthLetter(reviewCompanyBO.getAuthLetter());
        pendingCompany.setCommitUserId(reviewCompanyBO.getHrUserId());
        pendingCompany.setCommitUserMobile(reviewCompanyBO.getHrMobile());
        pendingCompany.setCommitDate(LocalDate.now());
        pendingCompany.setUpdatedTime(LocalDateTime.now());
        companyMapper.updateById(pendingCompany);
    }


    @Override
    public PageGridResult<List<CompanyInfoVO>> queryCompanyListPaged(QueryCompanyBO query, Integer page, Integer limit) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("companyName",query.getCompanyName());
        paramMap.put("realName",query.getCommitUser());
        paramMap.put("reviewStatus",query.getReviewStatus());
        paramMap.put("commitDateStart",query.getCommitDataStart());
        paramMap.put("commitDateEnd",query.getCommitDataEnd());
        PageHelper.startPage(page,limit);
        List<CompanyInfoVO> companyInfoVOS = companyCustomMapper.queryCompanyList(paramMap);

        return PageGridResult.of(companyInfoVOS,page);

    }

    @Override
    public CompanyInfoVO adminGetCompanyInfo(String companyId) {
        return companyCustomMapper.adminGetCompanyInfo(companyId);
    }

    @Override
    public void updateCompanyInfo(ReviewCompanyBO reviewCompanyBO) {
        Company pendingCompany = new Company();
        pendingCompany.setId(reviewCompanyBO.getCompanyId());
        pendingCompany.setReviewStatus(reviewCompanyBO.getReviewStatus());
        pendingCompany.setReviewReplay(reviewCompanyBO.getReviewReplay());
        pendingCompany.setUpdatedTime(LocalDateTime.now());
        companyCustomMapper.updateById(pendingCompany);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modifyCompanyInfo(ModifyCompanyInfoBO companyInfoBO) {
        String diskLock = "redis-lock";
        String selfId = UUID.randomUUID().toString();
        while (Boolean.FALSE.equals(stringRedisTemplate.opsForValue().setIfAbsent(diskLock, selfId, 5, TimeUnit.MINUTES))) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            doModify(companyInfoBO);
        }finally {
            String selfIdLock = stringRedisTemplate.opsForValue().get(diskLock);
            if (selfIdLock.equals(selfId)) {
                stringRedisTemplate.delete(diskLock);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void modifyCompanyInfoByRedisson(ModifyCompanyInfoBO companyInfoBO) {
        String diskLock = "redisson-lock";
        RLock lock = redissonClient.getLock(diskLock);
//        lock.lock(10,TimeUnit.SECONDS);
       try {
           doModify(companyInfoBO);
       }finally {
           lock.unlock();
       }
    }

    public void doModify(ModifyCompanyInfoBO companyInfoBO) {
        String companyId = companyInfoBO.getCompanyId();

        if (StringUtils.isBlank(companyId)) GraceException.disPlay(ResponseStatusEnum.COMPANY_INFO_UPDATED_NO_AUTH_ERROR);
        Company company = new Company();
        company.setId(companyId);
        company.setUpdatedTime(LocalDateTime.now());
        BeanUtils.copyProperties(companyInfoBO,company);
        companyMapper.updateById(company);
        stringRedisTemplate.delete(REDIS_COMPANY_MORE_INFO + ":" + companyId);
        stringRedisTemplate.delete(REDIS_COMPANY_BASE_INFO + ":" + companyId);
    }

    @Override
    public void saveCompanyPhoto(ModifyCompanyInfoBO companyInfoBO) {
        CompanyPhoto companyPhoto = new CompanyPhoto();
        companyPhoto.setCompanyId(companyInfoBO.getCompanyId());
        companyPhoto.setPhotos(companyInfoBO.getPhotos());
        //判断企业相册是否存在，不存在插入，存在就修改
        CompanyPhoto tempPhoto = getPhotoByCompanyId(companyInfoBO.getCompanyId());
        if (tempPhoto != null) {
            companyPhotoMapper.insert(tempPhoto);
        }else {
            companyPhotoMapper.update(companyPhoto,
                    new UpdateWrapper<CompanyPhoto>().eq("company_id",companyInfoBO.getCompanyId()));
        }

    }

    @Override
    public CompanyPhoto getPhotoByCompanyId(String companyId) {
        return companyPhotoMapper.getphotoByCompanyId(companyId);
    }
}
